package com.sondon.mayi.activity;

import org.androidannotations.annotations.App;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.sondon.mayi.application.ProjectApplication;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.util.LogUtil;
import com.sondon.mayi.util.MyPrefs_;
import com.sondon.mayi.util.ToastUtils;
import com.umeng.message.PushAgent;

import de.greenrobot.event.EventBus;

@EActivity
public class BaseActivity extends Activity {

	public static final String TAG = "BaseActivity";
	protected Context context = null;
	protected AlertDialog mAlertDialog;
	protected AsyncTask<?, ?, ?> mRunningTask;
	@App
	ProjectApplication OApplication;
	@Pref
	MyPrefs_ myprefs;

	// public static SharedPreferences perference;
	/**
	 * ***************************** 【Activity LifeCycle For
	 * Debug】******************************************
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		LogUtil.d(TAG, this.getClass().getSimpleName()+ " onCreate() invoked!!");
		super.onCreate(savedInstanceState);
		context = this;
		// 添加Activity到列表中
		OApplication.addActivity(this);
		
		//注册EventBus
		EventBus.getDefault().register(this);
		
		// Umeng统计应用启动数据
		PushAgent.getInstance(context).onAppStart();
		
//		myprefs=getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@Override
	protected void onStart() {
		LogUtil.d(TAG, this.getClass().getSimpleName() + " onStart() invoked!!");
		super.onStart();
	}

	@Override
	protected void onRestart() {
		LogUtil.d(TAG, this.getClass().getSimpleName()
				+ " onRestart() invoked!!");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		LogUtil.d(TAG, this.getClass().getSimpleName()
				+ " onResume() invoked!!");
		super.onResume();
	}

	@Override
	protected void onPause() {
		LogUtil.d(TAG, this.getClass().getSimpleName() + " onPause() invoked!!");
		super.onPause();
	}

	@Override
	protected void onStop() {
		LogUtil.d(TAG, this.getClass().getSimpleName() + " onStop() invoked!!");
		super.onStop();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		LogUtil.d(TAG, this.getClass().getSimpleName()+ " onDestroy() invoked!!");
		//停止AsyncTask任务
		if (mRunningTask != null && mRunningTask.isCancelled() == false) {
			mRunningTask.cancel(false);
			mRunningTask = null;
		}
		//注销EventBus
		EventBus.getDefault().unregister(this);
	}

	// eventbus事件
	public void onEventMainThread(Object event) {
		LogUtil.d("eventbus  shop", "BaseFragment ...");

	}
	

	/***************************************************** Toast **************************************************************/

	protected void showShortToast(int pResId) {
		showShortToast(getString(pResId));
	}

	protected void showLongToast(String pMsg) {
		Toast.makeText(this, pMsg, Toast.LENGTH_LONG).show();
	}

	protected void showShortToast(String pMsg) {
		Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show();
	}

	protected boolean hasExtra(String pExtraKey) {
		if (getIntent() != null) {
			return getIntent().hasExtra(pExtraKey);
		}
		return false;
	}

	/*************************************************** OpenActivity ******************************************************************/
	protected void openActivity(Class<?> pClass) {
		openActivity(pClass, null);
	}
	
	protected void openActivity_Login(Class<?> pClass) {
		if(myprefs.is_login().get()){
			openActivity(pClass, null);
		}else {
			ToastUtils.show(context, "请先登录!");
		}
	}

	protected void openActivity(Class<?> pClass, Bundle pBundle) {
		Intent intent = new Intent(this, pClass);
		if (pBundle != null) {
			intent.putExtras(pBundle);
		}
		startActivity(intent);
		/**
		 * 切换activity动画
		 * 在startActivity（）或finish（）后，调用overridePendingTransition（R.
		 * anim.**in,R.anim.**out）方法.
		 */
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	protected void openActivity(String pAction) {
		openActivity(pAction, null);
	}

	protected void openActivity(String pAction, Bundle pBundle) {
		Intent intent = new Intent(pAction);
		if (pBundle != null) {
			intent.putExtras(pBundle);
		}
		startActivity(intent);
	}

	protected void openActivityForResult(Class<?> pClass, Bundle pBundle,
			int requestCode) {
		Intent intent = new Intent(this, pClass);
		if (pBundle != null) {
			intent.putExtras(pBundle);
		}
		startActivityForResult(intent, requestCode);
	}

	/**
	 * 隐藏键盘
	 * 
	 * @param view
	 */

	protected void hideKeyboard(View view) {
		InputMethodManager imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(view.getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 内存空间不够
	 */
	protected void handleOutmemoryError() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(BaseActivity.this, "内存空间不足！", Toast.LENGTH_SHORT)
						.show();
				// finish();
			}
		});
	}

	/**
	 * finish
	 */
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}


	public void defaultFinish() {
		finish();
	}

	/**
	 * 
	 */
	public String getSD_Path() {
		// 获取sd卡路径
		String SDPath = Environment.getExternalStorageDirectory().getPath();

		String sdStatus = Environment.getExternalStorageState();
		// 检测sd是否可用
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			showShortToast("SD card is not avaiable/writeable right now.");
			SDPath = "";
		}
		return SDPath;
	}

	/**
	 * 返回 SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
	 * 
	 * @return
	 */
	public String getExternalFilesDirPath() {
		return context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
				.getAbsolutePath();
	}

	/**
	 * 返回 SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
	 * 
	 * @return
	 */
	public String getExStringCacheDir() {
		return context.getExternalCacheDir().getAbsolutePath();
	}

	public void isExit() {
		new AlertDialog.Builder(context).setTitle("确定退出吗?")
				.setNeutralButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 清空SharedPreferences
						// perference.edit().clear().commit();
						OApplication.exit();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				}).show();
	}
}
